<!DOCTYPE html>
<!--[if lt IE 7 ]><html lang="en" class="ie6 ielt7 ielt8 ielt9"><![endif]--><!--[if IE 7 ]><html lang="en" class="ie7 ielt8 ielt9"><![endif]--><!--[if IE 8 ]><html lang="en" class="ie8 ielt9"><![endif]--><!--[if IE 9 ]><html lang="en" class="ie9"> <![endif]--><!--[if (gt IE 9)|!(IE)]><!--> 
<html lang="en"><!--<![endif]--> 
	<head>
		<meta charset="utf-8">
		<title>成员</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<link href="css/bootstrap-responsive.min.css" rel="stylesheet">
		<link href="./assets/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">
		<link href="css/site.css" rel="stylesheet">
		<link rel="stylesheet" href="./css/tree-view.css">
		<!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
	</head>
	<body>
		<div class="container">
			<div class="navbar">
				<div class="navbar-inner">
					<div class="container">
						<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="#">Akira</a>
						<div class="nav-collapse">
							<ul class="nav">
								<li>
									<a href="role-table.html">角色管理</a>
								</li>
								<li>
									<a href="user-table.html">成员管理</a>
								</li>
								<li>
									<a href="city-tree.html">城市树</a>
								</li>
							</ul>
							<ul class="nav pull-right">
								<li>
									<a href="">@username</a>
								</li>
								<li>
									<a href="login.html">Logout</a>
								</li>
							</ul>
						</div>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="span3">
					<div class="well" style="padding: 8px 0;">
						<ul class="nav nav-list">
							<li>
								<a href="role-table.html"><i class="icon-list-alt"></i> 角色管理</a>
							</li>
							<li>
								<a href="user-table.html"><i class="icon-list-alt"></i> 成员管理</a>
							</li>
							<li class="active">
								<a href="city-tree.html"><i class="icon-white icon-list-alt"></i> 城市树</a>
							</li>
						</ul>
					</div>
				</div>
				<div class="span9">
					<h1>
						城市树
					</h1>
					<button class="btn btn-primary" id="addCityBtn" style="margin: 5px 25px;">新增城市</button>
					<div id="tree"></div>
				</div>
			</div>

			<!-- Modal -->
			<div class="modal fade" id="treeModal" tabindex="-1">
				<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
						<h4 class="modal-title" id="myModalLabel">Modal title</h4>
					</div>
					<div class="modal-body">
						<form class="form-horizontal">
							<!-- xxx名称 js改变label -->
							<div class="control-group">
								<label class="control-label nameLabel"><i class="required-star">*</i>Name</label>
								<div class="controls">
									<input type="text" class="input-xlarge nameInput">
								</div>
							</div>
							<!-- 排序值 label固定 值变化 -->
							<div class="control-group">
								<label class="control-label"><i class="required-star">*</i>排序值</label>
								<div class="controls">
									<input type="text" class="input-xlarge orderInput">
								</div>
							</div>

							<!-- <div class="form-group">
								<label class="col-sm-3 control-label"> 区间段:</label>
								<div class="col-sm-8">
									<input class="form-control" data-input-type="区间段" placeholder="" required="" type="" />
								</div>
							</div> -->
		
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
						<button type="button" class="btn btn-primary confirm">确定</button>
					</div>
				</div>
				</div>
			</div>

		</div>
		<script src="js/jquery.min.js"></script>
		<script src="js/bootstrap.min.js"></script>
		<script src="js/bootbox.min.js"></script>
		<script src="js/bootstrap-table.js"></script>
		<script src="js/bootstrap-table-zh-CN.js"></script>
		<script src="js/bootstrap-treeview.min.js"></script>
		<script src="js/site.js"></script>
		<script src="js/jquery.validate.min.js"></script>
		<script src="js/messages_zh.min.js"></script>
			
		<script>
				var levelNames = ['城市', '区域', '小区域'];
				var levelEng = ['city', 'area', 'region'];
			
				//url写在这
				var addUrls = {
					'城市':'a',
					'区域':'aa',
					'小区域':'aaa'
				}
				var editUrls = {
					'城市':'b',
					'区域':'bb',
					'小区域':'bbb'
				}
				var deleteUrls = {
					'城市':'c',
					'区域':'cc',
					'小区域':'ccc'
				}
			
			
				function getGoodDataFromRaw (rawData) {

					rawData.forEach(function(city, cityI) {
						rawData[cityI].icon = 'fa fa-globe';
						rawData[cityI].level = 0;
						if(rawData[cityI].nodes == undefined) return;

						rawData[cityI].nodes.forEach(function(area, areaI) {
							rawData[cityI].nodes[areaI].icon = 'fa fa-map-marker';
							rawData[cityI].nodes[areaI].level = 1;
							if(rawData[cityI].nodes[areaI].nodes == undefined) return;

							rawData[cityI].nodes[areaI].nodes.forEach(function(region, regionI) {
								rawData[cityI].nodes[areaI].nodes[regionI].icon = 'fa fa-map-pin';
								rawData[cityI].nodes[areaI].nodes[regionI].level = 2;
							});
						});
					});
					
					return rawData;
				}

				
				


			
				function initTree (rawData) {
					
					$('#tree').treeview({
						data: getGoodDataFromRaw(rawData),
						showBorder: false,
						collapseIcon: 'fa fa-angle-down',
						expandIcon: 'fa fa-angle-right',
						onNodeExpanded: function (e, node) {
							window.treeActions.push({
								isExpand: true,
								nodeId: node.nodeId
							});
						},
						onNodeCollapsed: function (e, node) {
							window.treeActions.push({
								isExpand: true,
								nodeId: node.nodeId
							});
						}
					});
			
					//添加城市按钮
					$('#addCityBtn').on('click', function() {
						//新增传入计算后的order
						//如果没有子node，默认设置为50
						var newOrder = 50;
						//如果有子node，找到里面最大的，+10
						if ($('#tree').treeview('getSiblings', '0') != undefined) {
							var siblingNodes = $('#tree').treeview('getSiblings', '0')[0].nodes;
							var siblingOrders = siblingNodes.map(function(val) {
								return val.order;
							});
						} else {
							var siblingOrders = [$('#tree').treeview('getSiblings', '0')[0].order];
						}
						newOrder = max(siblingOrders) + 10;
						
						var getAjaxData = function () {
							return {
								name: $('#treeModal .nameInput').val(),
								order: $('#treeModal .orderInput').val()
							}
						}
						openModal('新增城市', '城市名称', '', addUrls['城市'], getAjaxData, function(data) {
							doDependsResult(data, function () {
								loadTree();
								$('#treeModal').modal('hide');
							})
						}, newOrder);
					});
					
					/* 树上的按钮点击后 */
					$('#tree').on('click', '.addBtn', function() {
						var clickNode = getClickNode($(this));
						clickNode.parentId = clickNode.id;
						clickNode.id = null;
						console.log(clickNode);
						var levelName = levelNames[clickNode.level+1];
						var url = addUrls[levelName];

						var getAjaxData = function () {
							var ajaxData = {
								name: $('#treeModal .nameInput').val(),
								order: $('#treeModal .orderInput').val()
							}
							ajaxData[levelEng[clickNode.level] + 'Id'] = clickNode.parentId;
							return ajaxData;
						}

						//新增传入计算后的order
						//如果没有子node，默认设置为50
						var newOrder = 50;
						//如果有子node，找到里面最大的，+10
						if (clickNode.nodes != undefined) {
							var siblingNodes = clickNode.nodes;
							var siblingOrders = siblingNodes.map(function(val) {
								return val.order;
							});
							newOrder = max(siblingOrders) + 10;
						}
						openModal('新增' + levelName, levelName + '名称', '', url, getAjaxData, function(data) {
							doDependsResult(data, function () {
								loadTree();
								$('#treeModal').modal('hide');
							})
						}, newOrder);
					});


					$('#tree').on('click', '.editBtn', function() {
						var clickNode = getClickNode($(this));
						clickNode.parentId = $('#tree').treeview('getParent', clickNode).id;
						console.log(clickNode);
						var levelName = levelNames[clickNode.level];
						var url = editUrls[levelName];

						var getAjaxData = function () {
							return {
								id: clickNode.id,
								name: $('#treeModal .nameInput').val(),
								order: $('#treeModal .orderInput').val()
							}
						}

						//编辑传入当前order
						openModal('编辑'+levelName, levelName + '名称', clickNode.text, url, getAjaxData, function(data) {
							doDependsResult(data, function () {
								loadTree();
								$('#treeModal').modal('hide');
							})
						}, clickNode.order);
					});


					$('#tree').on('click', '.deleteBtn', function() {
						var clickNode = getClickNode($(this));
						clickNode.parentId = $('#tree').treeview('getParent', clickNode).id;
						console.log(clickNode);
						var levelName = levelNames[clickNode.level];

						bootbox.confirm('确认删除此项?', function (result) {
							if(!result) {
								return;
							}
							$.ajax({
								url: deleteUrls[levelName],
								data: {
									id: clickNode.id
								},
								success: function () {
									loadTree();
									$('#deleteModal').modal('hide');
								}
							});
						});
					});
				}
			
				function getClickNode ($btn) {
					//先select
					var nodeId = $btn.parents('li').data('nodeid');
					return $('#tree').treeview('getNode', nodeId);
				}
			
			
			
				/**
				 * label和value: 表单内input的label和值
				 * url和success: ajax的url和success
				 */
				function openModal(title, label, value, url, getAjaxData, success, order) {
					validator.resetForm();
			
					//设置modal
					$('#treeModal .modal-title').text(title);
					$('#treeModal .nameLabel').text(label);
					$('#treeModal .nameInput').val(value);
					//设置排序值
					$('#treeModal .orderInput').val(order);
					$('#treeModal button.confirm').unbind().click(function() {
						if(!validator.form()) {
							return;
						}
						$.ajax({
							url: url,
							data: getAjaxData(),
							type:'POST',
							success: success
						});
					});
					//显示modal
					$('#treeModal').modal('show');
				}
			
				function openDeleteModal (url, data, success) {
					$('#deleteModal button.confirm').unbind().click(function() {
						$.ajax({
							url: url,
							data: data,
							type:'POST',
							success: success
						});
					});
					//显示
					$('#deleteModal').modal('show');
				}
			
				function loadTree () {
					// $.ajax({
					// 	url: '/back/dictionary/region/data',
					// 	success: function(result) {

						var result = [{
							text: 'aa',
							icon: "fa fa-globe city",
							id: 111,
							order: 3,
							level: 0,
							nodes: [{
								text: 'aa',
								icon: "fa fa-map-marker city",
								id: 2222,
								order: 4,
								level: 1,
								nodes: [{
									text: 'aa',
									icon: "fa fa-map-pin city",
									id: 33333,
									order: 5,
									level: 2
								}, {
									text: 'aa',
									icon: "fa fa-map-pin city",
									id: 33333,
									order: 6,
									level: 2
								}, {
									text: 'aa',
									icon: "fa fa-map-pin city",
									id: 33333,
									order: 7,
									level: 2
								}]
							}, {
								text: 'aa',
								icon: "fa fa-map-marker city",
								id: 33333,
								order: 51,
								level: 1
							}, {
								text: 'aa',
								icon: "fa fa-map-marker city",
								id: 33333,
								order: 52,
								level: 1
							}, {
								text: 'aa',
								icon: "fa fa-map-marker city",
								id: 33333,
								order: 53,
								level: 1
							}]
						}];
						initTree(result);
		
						//按照已缓存的展开情况，对当前树进行展开
						if (window.treeActions.length > 0) {
							for(var i in window.treeActions) {
								var fn = window.treeActions[i].isExpand ? 'expandNode': 'collapseNode';
								$('#tree').treeview(fn, window.treeActions[i].nodeId);
							}
						}
					// 	}
					// });
				}
			
				$(function() {
					window.treeActions = [];
			
					loadTree();
			
					//hover有按钮
					$('#tree').on('mouseenter', 'li', function() {
						var level = $(this).find('span').length - 2;
						var addBtn;
						if(level < levelNames.length - 1) {
						  //  addBtn = '<a class="btn addBtn"><i class="fa fa-plus"></i> 新增'+levelNames[level+1]+'</a>';
							addBtn= getInsertStr(level);
						} else {
							addBtn = '';
						}
						//$(this).append('<div class="tree-btns">' + addBtn + ' <a class="btn editBtn"><i class="fa fa-pencil"></i> 编辑此' + levelNames[level] + '</a> <a class="btn deleteBtn"><i class="fa fa-trash"></i> 删除</a></div>');
						$(this).append('<div class="tree-btns">' + addBtn +getEditStr(level)+getDeleteStr()+'</div>');
					});
					$('#tree').on('mouseleave', 'li', function() {
						$this = $(this);
						$this.find('.tree-btns').remove();
					});
			
			
					window.validator = $('form').validate({
						ignore: ""
					});
			
				});

				getInsertStr = function(level){
					return '<a class="btn addBtn"><i class="fa fa-plus"></i> 新增'+levelNames[level+1]+'</a>';
				}
				getEditStr = function(level){
					return '<a class="btn editBtn"><i class="fa fa-pencil"></i> 编辑此' + levelNames[level] + '</a>';
				}
				getDeleteStr = function(){
					return '<a class="btn deleteBtn"><i class="fa fa-trash"></i> 删除</a>';
				}
			
				
			
			
			</script>
		
	</body>
</html>
